package com.bbcare.followup.plat.task;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import org.springframework.beans.factory.annotation.Autowired;

import com.bbcare.comm.PropertiesUtils;
import com.bbcare.followup.plat.service.IHisService;


/**
 * 广二HIS定时任务。
 */
public class GuangerHisJob implements Job {
    private final static Logger logger = Logger.getLogger(GuangerHisJob.class);
    private final static String PATIENT_LIST_TEMPLATE   = "guanger_query_patient_list.xml";
    private final static String PATIENT_LIST_DEMO   = "guanger_query_patient_list.demo.xml";
    private final static String PATIENT_DETAIL_TEMPLATE = "guanger_query_patient_detail.xml";
    private final static String PATIENT_DETAIL_DEMO = "guanger_query_patient_detail.demo.xml";
//    private final static String HIS_URL     = "http://192.168.3.174:57772/csp/jhip/JHIP.Query.BS.JHIPQuery.cls";
    private final static String HIS_URL     = "http://192.168.3.174/csp/jhip/JHIP.Query.BS.JHIPQuery.cls";
    private final static String SOAP_ACTION_LIST    = "http://tempuri.org/JHIP.Query.BS.JHIPQuery.QueryList";
    private final static String SOAP_ACTION_DETAIL  = "http://tempuri.org/JHIP.Query.BS.JHIPQuery.QueryDetailed";

    @Autowired
    private IHisService hisService;


    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        logger.info("++++execute() 广二定时任务开始执行。");
        String id,patientId,patSeqno,phone;
        int updated;
        final String hisTest= PropertiesUtils.getProperty("his_test");
        try {
            String soapMsg  = hisService.getResourceFile(PATIENT_LIST_TEMPLATE);
            String hisResult= null;
            if (StringUtils.isNotEmpty(hisTest) && (hisTest.equalsIgnoreCase("true") || hisTest.equalsIgnoreCase("yes")))   {
                hisResult   = hisService.getResourceFile(PATIENT_LIST_DEMO);
            } else {
                hisResult   = hisService.sendMessageToHis(HIS_URL, soapMsg, SOAP_ACTION_LIST);
                logger.info("++++execute() HIS返回数据如下：");
                logger.info(hisResult);
            }
            final List<Map> patientList = hisService.getPatientListFromSoap(hisResult);
            hisService.saveInPatientList(IHisService.GUANGER_TENANT_ID, patientList);
            for(Map patient : patientList)   {
                patientId   = patient.get(IHisService.MAPPER_PATIENT_ID).toString();
                patSeqno    = patient.get(IHisService.MAPPER_IN_SEQNO).toString();
                phone   = hisService.queryInPatientPhone(IHisService.GUANGER_TENANT_ID, patientId);
                if (StringUtils.isEmpty(phone) || StringUtils.isBlank(phone))    {
                    //发送查询患者详情的SOAP Message。
                    if (StringUtils.isNotEmpty(hisTest) && (hisTest.equalsIgnoreCase("true") || hisTest.equalsIgnoreCase("yes"))) {
                        hisResult   = hisService.getResourceFile(PATIENT_DETAIL_DEMO);
                    } else {
                        soapMsg = hisService.getResourceFile(PATIENT_DETAIL_TEMPLATE);
                        soapMsg = soapMsg.replaceAll("!PATIENTID", patSeqno);   //患者ID参数是流水号（不是患者ID）。
                        hisResult = hisService.sendMessageToHis(HIS_URL, soapMsg, SOAP_ACTION_DETAIL);
                    }
                    Map detailMap   = hisService.getPatientInfoFromSoap(hisResult);
                    phone   = detailMap.get(IHisService.MAPPER_PHONE).toString();
                    updated = hisService.updateInPatientPhone(phone, IHisService.GUANGER_TENANT_ID, patientId);
                    if (1 == updated)   {
                        logger.info("++++execute() succeed to update patientId:"+patientId+", phone:"+phone);
                    } else {
                        logger.error("----execute() fail to update patientId:"+patientId+", phone:"+phone);
                    }
                }
            }
        } catch (Exception ex)  {
            logger.error(ex.getMessage());
        }

        logger.info("++++execute() 广二定时任务结束执行。");
    }
}
